package com.llyb.chap02;

import java.util.concurrent.locks.ReentrantLock;

class Ticket{
    private Integer ticketNum = 100;

    private ReentrantLock lock = new ReentrantLock(false);
    public void sale(){
        lock.lock();
        try {
            while (ticketNum<=0){
                System.out.println("售完");
                return;
            }
            System.out.println(Thread.currentThread().getName()+"\t"+"---- 开始卖票 ");
            ticketNum--;
            System.out.println(Thread.currentThread().getName()+"\t"+"---- 卖出一张，剩余：" + ticketNum);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }


}

public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.sale();
            }
        },"A窗口").start();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.sale();
            }
        },"B窗口").start();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.sale();
            }
        },"C窗口").start();
    }
}
